package com.moncozgc.mall.controller;

import com.moncozgc.mall.common.CommonResult;
import com.moncozgc.mall.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 获取全局OID
 * 从 100000000000000, 一直累加. 数据存入redis中以便分布式集群使用
 */
@Slf4j
@RestController
public class OidGetController {

    @Autowired
    RedisService redisService;

    @GetMapping("/batchId")
    public CommonResult getOid(@RequestParam(name = "size", defaultValue = "1") Long size) {
        long ex_oid = Long.parseLong(redisService.get("get_oid"));
        AtomicLong at_oid = new AtomicLong(ex_oid);
        long MaxOID = ex_oid + size;
        List<String> oids = new ArrayList<>();
        for (; ex_oid < MaxOID; ex_oid++) {
            oids.add(String.format("%015d", at_oid.getAndIncrement()));
        }
        log.info("获取全局OID, 数量: " + size);
        redisService.set("get_oid", String.valueOf(ex_oid));
        return CommonResult.success(oids);
    }

    /**
     * 获取指定位数的随机数字
     */
    private String generateOid(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
}
